package com.cyx.service;

import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import com.cyx.entity.Education;
import com.cyx.entity.User;
import com.cyx.utils.FileUtils;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.font.FontProvider;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.util.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;

    public void userInfoExport(HttpServletResponse response) throws Exception {
        // 获得对象
        User user = getUser();
        // 获得对象模型(模板变量)
        Map dataMap = JSON.parseObject(JSON.toJSONStringWithDateFormat(user, "yyyy-MM-dd"), Map.class);
        // 对象模型 + ftl模板 -> html
        String content = getHtmlContent(dataMap);
        // 设置使用字体
        ConverterProperties properties = new ConverterProperties();
        setFont(properties);
        // 设置响应头
        OutputStream os = response.getOutputStream();
        FileUtils.setAttachmentResponseHeader(response, user.getUserName() + "个人信息.pdf");
        // html -> pdf
        HtmlConverter.convertToPdf(content, os, properties);
        os.flush();
        os.close();
    }

    /**
     * 获得对象
     */
    private User getUser() {
        Education e1 = Education.builder().system("全日制").level("研究生").degree("硕士学位").university("四川大学").major("软件工程").build();
        Education e2 = Education.builder().system("全日制").level("博士生").degree("博士学位").university("四川大学").major("机器智能与类脑计算").build();
        List<Education> educations = new ArrayList<>();
        educations.add(e1);
        educations.add(e2);

        return User.builder()
                .userId(155)
                .userName("Lee")
                .sex("男")
                .birthday(LocalDate.now())
                .photoUrl("https://profile-avatar.csdnimg.cn/9ce72c229ba24395843a06daa6934fd5_qq_38058241.jpg")
                .nationality("汉族")
                .hometown("四川成都")
                .phone("13588889999")
                .email("amy1055@gmail.com")
                .introduction("本人性格热情开朗，待人友好，为人诚实谦虚。\n" +
                        "工作勤奋，认真负责，能吃苦耐劳，尽职尽责，有耐心。\n" +
                        "具有亲和力，平易近人，善于与人沟通。\n" +
                        "学习刻苦认真，成绩优秀，名列前茅。\n" +
                        "品学兼优，连续三年获得学院奖学金。")
                .educationList(educations)
                .build();
    }

    /**
     * 根据模板获得html
     */
    private String getHtmlContent(Map data) {
        Writer out = new StringWriter();
        try {
            Configuration freemarkerCfg = freeMarkerConfigurer.getConfiguration();
            Template template = freemarkerCfg.getTemplate("ftl-templates/user_personal.ftl");
            // 合并数据模型与模板
            template.process(data, out); //将合并后的数据和模板写入到流中，这里使用的字符流
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 设置使用字体
     */
    private void setFont(ConverterProperties properties) throws Exception {
        FontProvider font = new FontProvider();
        //设置自定义字体
        ClassPathResource classPathResource = new ClassPathResource("font/simhei.ttf");
        InputStream is = classPathResource.getInputStream();
        byte[] fontBytes = IOUtils.toByteArray(is);
        PdfFont pf = PdfFontFactory.createFont(fontBytes, CharsetUtil.UTF_8, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED, true);
        font.addFont(pf.getFontProgram());
        properties.setFontProvider(font);
    }
}
